package week_07;

public class SurroundedRegions_130 {
    int[] dx = new int[]{-1, 0, 0, 1};
    int[] dy = new int[]{0, -1, 1, 0};
    int[] fa;
    int m;
    int n;

    public void solve(char[][] board) {
        m = board.length;
        n = board[0].length;

        fa = new int[m * n+1];

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                fa[num(i, j)] = num(i, j);
            }
        }
        fa[n * m] = m * n;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'X') continue;
                for (int k = 0; k < 4; k++) {
                    int nx = i + dx[k];
                    int ny = i + dy[k];
                    // 走一步就越界 说明x,y 就是边部点
                    if (nx < 0 || ny < 0 || nx >= m || ny >= n) {
                        fa[get(num(i, j))] = get(m * n);
                    }else if(board[nx][ny]=='O') {
                        fa[get(num(nx, ny))] = get(num(i, j));
                    }
                }
            }
        }
        // 分好并查集块
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O' && get(num(i,j)) !=get( m * n)) {
                    board[i][j] = 'X';
                }
            }
        }

    }

    public int get(int x) {
        return x == fa[x] ? x : (fa[x] = get(fa[x]));
    }

    public int num(int i, int j) {
        return i * n + j;
    }
}
